'use strict';

const _ = require('lodash');
const path = require('path');
const fs = require('fs');
const {exec} = require('child_process');
const {Controller} = require('ee-core');
const {
    app: electronApp, dialog, shell, BrowserView, session, Notification, sessionpowerMonitor, screen, nativeTheme
} = require('electron');
const Ps = require('ee-core/ps');
const Log = require('ee-core/log');
const dayjs = require('dayjs');


/**
 * Cookies控制器
 * @class
 */
class CookiesController extends Controller {

    constructor(ctx) {
        super(ctx);
    }

    //获取cookies
    async getCookies(arg) {
        try {
            const {url, partition} = arg
            const sess = session.fromPartition(partition)
            const result = await sess.cookies.get({url: url});
            return {code: 200, message: "获取Cookies成功", data: {list: result}}

        } catch (err) {

            return {code: 401, message: "获取Cookies请求失败"}
        }

    }


    //设置cookies
    async setCookies(arg) {
        try {
            const {url, partition, cookies} = arg
            const sess = session.fromPartition(partition)
            await this.removeCookie(arg)
                for(let cookie of cookies){
                    sess.cookies.set({url,name:cookie.name,value:cookie.value,domain:cookie.domain,path:cookie.path})
                        .then(res=>{})
                        .catch(err=>{})
                }
            console.log(arg.url, "设置Cookies")
            return {code: 200, message: "设置Cookies成功", data: {list: []}}

        } catch (err) {
            return {code: 401, message: "设置Cookies失败"}
        }
    }


    //删除Cookies
    async removeCookie(arg) {
        const {url, partition} = arg
        const sess = session.fromPartition(partition) //'persist:github'
        const cookies = await sess.cookies.get({url})
        console.log(url, cookies);
        for (let cookie of cookies) {
            await sess.cookies.remove(url, cookie.name)
        }
        console.log(arg.url, "删除事件");

        return {code: 200, message: "删除Cookies成功", data: {list: []}}
    }


}

CookiesController.toString = () => '[class ExampleController]';
module.exports = CookiesController;
